
package cn.itcast.Annotation;


import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    private static ObjectMapper mapper = new ObjectMapper();

    @Value("${cache.enable}")
    private Boolean enable;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断是否开启系统全局缓存
        if (!enable){
            //如果没有开启 直接放行
            return true;
        }

        //判断是不是handler里面的方法
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断是不是Get请求
        if (!((HandlerMethod)handler).hasMethodAnnotation(GetMapping.class)){

            return true;
        }

        //controller未加Cache注解
        if (!((HandlerMethod)handler).hasMethodAnnotation(Cache.class)){
            return true;
        }

        //从缓存中取
        String redisKey = createRedisKey(request);
        String data = redisTemplate.opsForValue().get(redisKey);
        System.out.println("data = " + data);

        //缓存中没有
        if (StringUtils.isEmpty(data)){
            return true;
        }

        //缓存中有
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(data);
        return false;
    }

    //生成唯一redisKey
    public static String createRedisKey(HttpServletRequest request) throws IOException {

        String url = request.getRequestURI();

        String param = mapper.writeValueAsString(request.getParameterMap());
        String token = request.getHeader("Authorization");
        String data = url +"_" + param + "_" +token;
        return "health@"+ DigestUtil.md5Hex(data);
    }

}

